<template>
  <div class="followup-box inner-content">
    <div class="inner inner-content-box">
      <div class="searchBox">
        <el-form
          :inline="true"
          :model="searchForm"
          size="small"
          style="width: 100%"
        >
          <el-form-item label="考试名称">
            <el-input
              v-model="searchForm.stationNumber"
              type="number"
              placeholder="考试名称"
              clearable
              style="width: 160px"
            ></el-input>
          </el-form-item>
          <el-form-item label="考试时间">
             <el-date-picker
              v-model="searchForm.examDate"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 280px"
              >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="getList"
              size="small"
              icon="el-icon-search"
              >搜索</el-button
            >
            <el-button @click="searchReset" size="small" icon="el-icon-delete"
              >清空</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <div class="detailsBox">
        <ag-grid-vue
          class="ag-theme-alpine ag-theme-quartz"
          :gridOptions="gridOptions"
          :localeText="localeText"
          @grid-ready="onGridReady"
          @sort-changed="onSortChangedAggrid"
          @filter-changed="onFilterChangedAggrid"
          :rowHeight="38"
          :headerHeight="42"
          :columnDefs="columnDefs"
          :defaultColDef="defaultColDef"
          :rowData="rowData"
          rowSelection="multiple"
          :rowMultiSelectWithClick="true"
          :enableRangeSelection="true"
        >
        </ag-grid-vue>
      </div>
      <div class="pageBox">
        <div>
        </div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.currentPage"
          :page-sizes="page.pageSizes"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
        >
        </el-pagination>
      </div>
    </div>
    <examCommonDetails ref='examCommonDetails' :showCommonDetails='showCommonDetails' @closeCommonDetails='closeCommonDetails' :chooseObj='chooseObj' :isXiShuFlag='isXiShuFlag' :xiShuStandard='xiShuStandard' :passScore='passScore' :passScorePercent='setFormB.passScorePercent'></examCommonDetails>
    <!-- 系数设置 A start -->
    <el-dialog
      title="系数设置"
      :visible="showCoefficient"
      :before-close="handleCloseCoefficient"
      width="800px">
      <div class="innerBoxDialog">
        <div class="p_title">考试信息</div>
        <div class="box_title">
        <div class="title-inner">
          <p class="first">考试：</p>
          <p class="second" style="color: #00b99e;">{{ chooseObj.recordsName }}</p>
        </div>
        <div class="title-inner">
          <p class="first" style="font-weight: 400;font-size: 14px;">起止日期：</p>
          <p class="second" style="font-weight: 500;font-size: 14px;">{{ chooseObj.examStartDate }} 至 {{ chooseObj.examEndDate }}</p>
        </div>
      </div>
        <div class="contentBox">
          <div style="padding:20px 0 10px;font-size: 16px;font-weight: 500;">请设置核算比重</div>
          <el-form ref="setForm" :model="setForm" label-width="120px" style="padding:  0 100px;">
            <el-row>
              <el-col :span="12" v-for="(item,index) in examRecordsStationEntities" :key='index'>
                <el-form-item :label="item.stationName">
                  <el-input v-model="item.xishu" placeholder='请输入系数' type="number"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设置通过标准">
                  <el-input v-model="passScore" placeholder='设置通过标准' type="number"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
          </el-form>
          <span class="dialog-footer" style="display: flex;justify-content: center;">
            <el-button @click="handleCloseCoefficient">取 消</el-button>
            <el-button type="primary" @click="submitSetForm">确 定</el-button>
          </span>
        </div>
      </div>
    </el-dialog>
    <!-- 系数设置 A end -->

    <!-- 系数设置 B start -->
    <el-dialog
      title="系数设置"
      :visible="showCoefficientB"
      :before-close="handleCloseCoefficientB"
      width="800px">
      <div class="innerBoxDialog">
        <div class="p_title">考试信息</div>
        <div class="box_title">
        <div class="title-inner">
          <p class="first">考试：</p>
          <p class="second" style="color: #00b99e;">{{ chooseObj.recordsName }}</p>
        </div>
        <div class="title-inner">
          <p class="first" style="font-weight: 400;font-size: 14px;">起止日期：</p>
          <p class="second" style="font-weight: 500;font-size: 14px;">{{ chooseObj.examStartDate }} 至 {{ chooseObj.examEndDate }}</p>
        </div>
      </div>
        <div class="contentBox">
          <div style="padding:20px 0 10px;font-size: 16px;font-weight: 500;">及格分数标准</div>
          <el-form ref="setFormB" :model="setFormB" :rules='setFormBRule' label-width="120px" style="padding:  0 100px;">
            <el-row>
              <el-col :span="18">
                <el-form-item label="及格分数标准">
                  <el-input v-model="setFormB.passScorePercent" placeholder='及格分数标准' type="number"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
          </el-form>
          <span class="dialog-footer" style="display: flex;justify-content: center;">
            <el-button @click="handleCloseCoefficientB">取 消</el-button>
            <el-button type="primary" @click="submitSetFormB">确 定</el-button>
          </span>
        </div>
      </div>
    </el-dialog>
    <!-- 系数设置 B end -->

  </div>
</template>
<script>
// import Vue from 'vue'
import listBtn from '@/views/modules/examinationScore/listBtn.vue'
import listJson from '@/views/modules/examinationScore/list.json'
import examCommonDetails from '@/views/modules/examinationScore/examCommonDetails.vue'
import { fetchList } from '@/api/examTest.js'
import { listByRecordsId, recordsxishuSave, recordsxishuSaveB } from '@/api/examinationScore.js'

export default {
  beforeMount () {
    this.gridOptions = {
      // 通过这个属性建立了上下文引用
      context: { componentParent: this }
      // 说人话就是可以在自己声明的组件里调用到父组件的方法和属性了
    }
  },
  components: {
    listBtn,
    examCommonDetails
  },
  watch: {
    $route: {
      handler (newValue, oldValue) {
        console.log(11111)
        if (oldValue.name === 'examinationScore-list') {
          console.log(22222222)
          this.showCommonDetails = false
          this.showCoefficient = false
          this.showCoefficientB = false
          this.isXiShuFlag = false
          this.$refs.examCommonDetails.allClose()
        }
      },
      deep: true
    }
  },
  data () {
    return {
      gridOptions: null,
      localeText: this.$AG_GRID_LOCALE_ZZZ,
      col: [],
      page: {
        pageSizes: [100, 2000, 5000],
        currentPage: 1,
        total: 0,
        pageSize: 100
      },
      searchForm: {
        stationNumber: ''
      },
      defaultColDef: {
        editable: false,
        sortable: true,
        resizable: true,
        filter: true,
        cellDataType: false
      },
      rowIndexArr: [
        {
          field: 'rowIndex',
          headerName: '序号',
          width: 100,
          checkboxSelection: false,
          headerCheckboxSelection: false,
          sortable: false,
          pinned: 'left',
          valueGetter: (params) => {
            // 返回当前行的序号
            return params.node.rowIndex + 1
          }
        },
        {
          field: 'handle',
          headerName: '操作',
          width: 150,
          pinned: 'right',
          cellRenderer: 'listBtn'
        }
      ],
      columnDefs: [],
      gridApi: null,
      rowData: [],
      msg: null,
      showCommonDetails: false,
      // 系数查看
      showCoefficient: false,
      chooseObj: {},
      // 比值
      setForm: {
        first: '0.1'
      },
      examRecordsStationEntities: [],
      passScore: '',
       // 是否有系数
      isXiShuFlag: false,
      xiShuStandard: '',

      showCoefficientB: false,
      setFormB: {
        passScorePercent: ''
      },
      setFormBRule: {
        passScorePercent: [
          {
            required: true,
            message: '及格分数标准不能为空',
            trigger: 'blur'
          }
        ]
      }

    }
  },
  created () {
    this.getHeadersCol()
    setTimeout(() => {
      this.getList()
    }, 10)
  },
  methods: {
    onSortChangedAggrid (event) {
      const api = event.api
      const visibleRowCount = api.getDisplayedRowCount()
      for (let i = 0; i < visibleRowCount; i++) {
        const rowNode = api.getDisplayedRowAtIndex(i)
        console.log(rowNode)
      }
      let aaa = JSON.parse(JSON.stringify(this.rowData))
      if (this.gridApi.getRenderedNodes().length > 1) {
        this.aggridScrollNum = this.gridApi.getRenderedNodes()[1].rowIndex - 1
      } else {
        this.aggridScrollNum = this.gridApi.getRenderedNodes()[0].rowIndex
      }
      setTimeout(() => {
        this.rowData = JSON.parse(JSON.stringify(aaa))
        setTimeout(() => {
          if (this.aggridScrollNum !== 0) {
            this.gridApi.ensureIndexVisible(this.aggridScrollNum, 'top')
          }
        }, 10)
      }, 10)
    },
    onFilterChangedAggrid (event) {
      const api = event.api
      const visibleRowCount = api.getDisplayedRowCount()
      for (let i = 0; i < visibleRowCount; i++) {
        const rowNode = api.getDisplayedRowAtIndex(i)
        console.log(rowNode)
      }
      let aaa = JSON.parse(JSON.stringify(this.rowData))
      if (this.gridApi.getRenderedNodes().length > 1) {
        this.aggridScrollNum = this.gridApi.getRenderedNodes()[1].rowIndex - 1
      } else {
        this.aggridScrollNum = this.gridApi.getRenderedNodes()[0].rowIndex
      }
      setTimeout(() => {
        this.rowData = JSON.parse(JSON.stringify(aaa))
        setTimeout(() => {
          if (this.aggridScrollNum !== 0) {
            this.gridApi.ensureIndexVisible(this.aggridScrollNum, 'top')
          }
        }, 10)
      }, 10)
    },
    // 获取表头
    getHeadersCol () {
      this.columnDefs = []
      setTimeout(() => {
        this.col = JSON.parse(JSON.stringify(listJson.column))
        this.columnDefs = this.rowIndexArr.concat(this.col)
      }, 10)
    },
    // 装载列表
    onGridReady (params) {
      this.gridApi = params.api
    },
    getList () {
      let params = {
        limit: this.page.pageSize,
        page: this.page.curentPage,
        stationNumber: this.searchForm.stationNumber || '',
        // 状态1 是已完成的考试 必须要有
        examStatus: 1,
        orderSql: 'totalStationNumber asc'
      }
      fetchList(params).then(res => {
        this.rowData = res.data.page.records
        this.page.total = res.data.page.total
      })
    },
    handleSizeChange (val) {
      this.page.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      this.page.currentPage = val
      this.getList()
    },
    // 清空搜索
    searchReset () {
      this.searchForm = {}
      this.page.currentPage = 1
      // this.getList();
    },

    resetForm () {
      this.$refs['addOrUpdateForm'].resetFields()
    },
    // 普通查看
    viewCommonHandle (val) {
      this.chooseObj = val
      this.showCommonDetails = true
      this.isXiShuFlag = false
      setTimeout(() => {
        this.$refs.examCommonDetails.onCommonShow()
        // 考站维度
        this.$refs.examCommonDetails.getRecordsExamResultStation()
        // 考题维度
        this.$refs.examCommonDetails.getRecordsExamResultExam()
        // 得分项维度
        this.$refs.examCommonDetails.getExamExaminationList()
        // 考生维度
        this.$refs.examCommonDetails.getRecordsExamResultPage()
      }, 10)
    },
    closeCommonDetails () {
      this.showCommonDetails = false
    },
    // 获取系数
    getListByRecordsId () {
      let params = {
        recordsId: this.chooseObj.id
      }
      listByRecordsId(params).then(res => {
        this.examRecordsStationEntities = res.data.data.examRecordsStationEntities
        if (res.data.data.passScore) {
          this.passScore = res.data.data.passScore
        } else {
          this.passScore = ''
        }
        if (res.data.data.recordsXishuEntityList.length === 0) {
          this.examRecordsStationEntities.map(it => {
            it.xishu = ''
          })
        } else {
          this.examRecordsStationEntities = res.data.data.recordsXishuEntityList
        }
        setTimeout(() => {
          let aaa = this.examRecordsStationEntities.sort((a, b) => parseInt(a.stationName.substring(1, 2)) - parseInt(b.stationName.substring(1, 2)))
          // let aaa = JSON.parse(JSON.stringify(this.examRecordsStationEntities))
          this.examRecordsStationEntities = []
          this.examRecordsStationEntities = JSON.parse(JSON.stringify(aaa))
          this.showCoefficient = true
        }, 10)
      })
    },
    // 驾驶舱查看
    viewDriverHandle (val) {
      this.$router.push({name: 'thisTimeCockpit', query: {recordsName: val.recordsName, recordsId: val.id, type: val.type}, params: {recordsName: val.recordsName, recordsId: val.id, type: val.type}})
    },
    // 考试分析报告
    viewAnalysisHandle (val) {
      this.$http({
        url: '/excel/student/getRecordsReport',
        method: 'post',
        responseType: 'blob',
        params: { recordsId: val.id }
      }).then(({ data }) => {
        var binaryData = []
        binaryData.push(data)
        let blob = new Blob(binaryData, {
          type: 'application/msword'
        })
        setTimeout(() => {
          if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, 'link')
          } else {
            const link = document.createElement('a')
            console.log(window.URL.createObjectURL)

            link.download = val.recordsName
            link.style.display = 'none'
            link.href = window.URL.createObjectURL(blob)
            document.body.appendChild(link)
            link.click()
            URL.revokeObjectURL(link.href)
            document.body.removeChild(link)
            this.$message.success(`${val.recordsName}导出成功`)
          }
        })
      }).catch(err => {
        console.log(err)
      })
    },
    // 系数查看   A
    viewHandle (val) {
      this.chooseObj = JSON.parse(JSON.stringify(val))
      setTimeout(() => {
        this.getListByRecordsId()
      }, 10)
    },
    // 系数查看   B
    viewHandleB (val) {
      this.chooseObj = JSON.parse(JSON.stringify(val))
      setTimeout(() => {
        // this.getListByRecordsIdB()
        this.setFormB.passScorePercent = this.chooseObj.passScorePercent
        this.showCoefficientB = true
      }, 10)
    },
    getListByRecordsIdB () {

    },
    // 关闭系数
    handleCloseCoefficient () {
      this.showCoefficient = false
    },
    // 关闭B类系数
    handleCloseCoefficientB () {
      this.showCoefficientB = false
    },
    // 保存系数  B
    submitSetFormB () {
      let params = {
        id: this.chooseObj.id,
        passScorePercent: Number(this.setFormB.passScorePercent)
      }
      recordsxishuSaveB(params).then(res => {
        this.showCommonDetails = true
        this.isXiShuFlag = false
        setTimeout(() => {
          this.$refs.examCommonDetails.onCommonShow()
        // 考站维度
          this.$refs.examCommonDetails.getRecordsExamResultStation()
        // 考题维度
          this.$refs.examCommonDetails.getRecordsExamResultExam()
        // 得分项维度
          this.$refs.examCommonDetails.getExamExaminationList()
        // 考生维度
          this.$refs.examCommonDetails.getRecordsExamResultPage()
        }, 10)
        console.log(res)
      })
    },
    // 保存系数
    submitSetForm () {
      let allCount = false
      this.examRecordsStationEntities.map(it => {
        if (!it.xishu) {
          allCount = true
        }
      })
      if (allCount) {
        this.$message.warning('请检查系数是否填写正确')
        return
      }
      let count = 0
      this.examRecordsStationEntities.map(it => {
        count += Number(it.xishu)
      })
      if (count !== 1) {
        this.$message.warning('系数总分需要等于1，请检查')
        return
      }
      if (!this.passScore) {
        this.$message.warning('请输入设置通过标准')
        return
      }
      let params = {
        recordsId: this.chooseObj.id,
        passScore: Number(this.passScore)
      }
      let arr = []
      this.examRecordsStationEntities.map(it => {
        arr.push({
          stationName: it.stationName,
          xishu: Number(it.xishu)
        })
      })
      params.recordsXishuEntityList = arr
      recordsxishuSave(params).then(res => {
        // 有系数
        this.isXiShuFlag = true
        this.xiShuStandard = ''
        this.examRecordsStationEntities.map(v => {
          this.xiShuStandard += `+ ${v.stationName} * ${v.xishu} `
        })
        this.xiShuStandard = this.xiShuStandard.substring(2)
        this.showCoefficient = false
        this.showCommonDetails = true
        setTimeout(() => {
          this.$refs.examCommonDetails.onCommonShow()
          // 考站维度
          this.$refs.examCommonDetails.getRecordsExamResultStation()
          // 考题维度
          this.$refs.examCommonDetails.getRecordsExamResultExam()
          // 得分项维度
          this.$refs.examCommonDetails.getExamExaminationList()
          // 考生维度
          this.$refs.examCommonDetails.getRecordsExamResultPage()
        }, 10)
        console.log(res)
      })
    }
  }
}
</script>
<style lang='scss'>
.el-range-separator{
  z-index: 1000 !important;
}
.el-dialog__body{
    padding: 10px;
  }
.innerBoxDialog{
  width: 100%;
  margin: 0 auto;
  // background: pink;
  border: 1px solid #00b99e;
  overflow: auto;
  padding: 20px 20px;
  border-radius: 6px;
  .p_title{
    color: #000;
    font-size: 18px;
    font-weight: 500;
    position: relative;
  }
  .p_title:before{
    content: '';
    height: 80%;
    width: 4px;
    background: #00b99e;
    border-radius: 4px;
    position: absolute;
    left: -10px;
    top: 2px;
  }
  .box_title{
    height: 40px;
    width: 100%;
    background: #00b99e40;
    margin: 10px 0;
    border-radius: 2px;
  }
  .contentBox{
    border: 1px solid #00b99e;
    padding: 10px;
    border-radius: 6px;
  }
}
</style>
